package com.example.gateway;

import com.example.buildtable.pojo.Member;
import com.example.buildtable.pojo.User;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        String username = queryParams.getFirst("username");
        String password = queryParams.getFirst("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        String memberAccount = queryParams.getFirst("memberAccount");
        String memberPassword = queryParams.getFirst("password");
        Member member = new Member();
        member.setMemberAccount(memberAccount);
        member.setPassword(memberPassword);


        if (username != null && password != null && username.equals(user.getUsername()) && password.equals(user.getPassword())) {
            // 执行后续的过滤器
            return chain.filter(exchange);
        }

        if (memberAccount != null && memberPassword != null && memberAccount.equals(member.getMemberAccount()) && memberPassword.equals(member.getPassword())) {
            // 执行后续的过滤器
            return chain.filter(exchange);
        }

        // 拦截，禁止访问
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }
}